import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/Home.vue'
import { getUserInfo } from '../api/user.js'
import { nextTick } from 'vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { title: '首页', icon: 'HomeFilled', top: true }
  },
  {
    path: '/info',
    name: 'Info',
    component: () => import('@/views/Info.vue')
  },
  {
    path: '/Servers',
    name: 'Servers',
    meta: { title: '业务服务', icon: 'Setting', top: true },
    children: [
      {
        path: 'menu-management',
        name: 'MenuManagement',
        component: () => import('@/views/Servers/MenuManagement.vue'),
        meta: { title: '菜单管理', icon: 'Menu' }
      },
      {
        path: 'role-management',
        name: 'RoleManagement',
        component: () => import('@/views/Servers/RoleManagement.vue'),
        meta: { title: '角色管理', icon: 'User' }
      },
      {
        path: 'employee-management',
        name: 'EmployeeManagement',
        component: () => import('@/views/Servers/EmployeeManagement.vue'),
        meta: { title: '用户管理', icon: 'UserFilled' }
      },
      {
        path: 'dept-management',
        name: 'DeptManagement',
        component: () => import('@/views/Servers/DeptManagement.vue'),
        meta: { title: '部门管理', icon: 'UserFilled' }
      },
      {
        path: 'job-management',
        name: 'JobManagement',
        component: () => import('@/views/Servers/JobManagement.vue'),
        meta: { title: '岗位管理', icon: 'User' }
      }
    ]
  },
  {
    path: '/user',
    name: 'User',
    meta: { title: '我的空间', icon: 'Monitor', top: true },
    children: [
      {
        path: 'myorder',
        name: 'MyOrder',
        component: () => import('@/views/ownerSpace/MyOrder.vue'),
        meta: { title: '我的订单', icon: 'List' }
      },
      {
        path: 'photowall',
        name: 'PhotoWall',
        component: () => import('@/views/ownerSpace/PhotoWall.vue'),
        meta: { title: '我的照片', icon: 'Picture' }
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login.vue'),
  },
  {
    path: '/error',
    name: 'error',
    component: () => import('@/views/error.vue'),
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

const getLogined = async () => {
  const res = await getUserInfo()
  if (res != null) {
    if (res.status == '200') {
      return 1
    } else {
      return 0
    }
  } else {
    return -1
  }
}

router.afterEach(async (to, from, next) => {
  if(to.name == from.name)
    return
  const logined = await getLogined()
  if(logined == -1){
    router.push({name:'error'})
  } else {
    if(logined == 1 && to.name == "login"){
      router.push({name:'Home'})
    } else if(logined == 0 && to.name != 'login'){
      router.push({name:'login'})
    }
  }

});


export default router